package org.javascud.extensions.cxf.zookeeper.server;

import org.apache.cxf.endpoint.Server;
import org.apache.cxf.jaxws.JaxWsServerFactoryBean;
import org.apache.zookeeper.ZooKeeper;
import org.javascud.extensions.cxf.service.Hello;
import org.javascud.extensions.zookeeper.GroupMemberCenter;


public class HelloServicePublisher5Zookeeper
{
    public static String zkAddress = "127.0.0.1:2181";
    public static String groupName = "helloservice";

    public void start(final String address, final Hello hello)  throws Exception
    {
        startService(address, hello);

        //register into zookeeper
        register2Zookeeper(address);
    }

    private void startService(String address, Hello hello)
    {
        JaxWsServerFactoryBean factory = new JaxWsServerFactoryBean();
        factory.setServiceClass(Hello.class);
        factory.setServiceBean(hello);

        //factory.setAddress("http://localhost:8080/service/HelloWorld");
        factory.setAddress(address);

        Server server = factory.create();
        server.start();
    }

    private void register2Zookeeper(String address) throws Exception
    {
        ZooKeeper zk = new ZooKeeper(zkAddress, 3000, null);

        GroupMemberCenter gmc = new GroupMemberCenter();
        gmc.setZooKeeper(zk);

        gmc.createAndSetGroup(groupName);
        gmc.joinGroupByDefine(address);

        System.out.println("register service to zookeeper: " + address);
    }
}